<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="JinYan&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/blog/css/images/logo.jpg">
  
  <title>
    
      Python-3-模块 | SanYuanEmpire
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/blog/css/style.css">
<link rel="stylesheet" href="/blog/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/blog/js/qrious.js"></script>
<script src="/blog/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.jpg" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/blog/">
      <div class="logo"></div>
      <span>SanYuanEmpire</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/blog/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/blog/archives/" class="item-link">Archives</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/blog/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/blog/archives/" class="menu-link">Archives</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Python-3-模块</h2>
  <p class="post-date">2018-09-03</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h1><blockquote>
<p>编写模块有很多种方法，其中最简单的一种便是创建一个包含函数与变量、以 .py 为后缀的文件。<br>另一种方法是使用撰写 Python 解释器本身的本地语言来编写模块。举例来说，你可以使用 C 语言来撰写 Python 模块，并且在编译后，你可以通过标准 Python 解释器在你的 Python 代码中使用它们。<br>模块是一个包含所有你定义的函数和变量的文件，其后缀名是.py。模块可以被别的程序引入，以使用该模块中的函数等功能。这也是使用 Python 标准库的方法。<br>当解释器遇到 import 语句，如果模块在当前的搜索路径就会被导入。<br>搜索路径是一个解释器会先进行搜索的所有目录的列表。如想要导入模块，需要把命令放在脚本的顶端。<br>一个模块只会被导入一次，这样可以防止导入模块被一遍又一遍地执行。<br>搜索路径被存储在 sys 模块中的 path 变量。当前目录指的是程序启动的目录。</p>
</blockquote>
<h2 id="导入模块"><a href="#导入模块" class="headerlink" title="导入模块"></a>导入模块</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">导入模块：</span><br><span class="line">import module1[, module2[,... moduleN]]</span><br><span class="line">从模块中导入一个指定的部分到当前命名空间中：</span><br><span class="line">from modname import name1[, name2[, ... nameN]]</span><br><span class="line">把一个模块的所有内容全都导入到当前的命名空间：</span><br><span class="line">from modname import *</span><br></pre></td></tr></table></figure>
<h1 id="name-属性"><a href="#name-属性" class="headerlink" title="name 属性"></a><strong>name</strong> 属性</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">每个模块都有一个 __name__ 属性，当其值是 &apos;__main__&apos; 时，表明该模块自身在运行，否则是被引入。</span><br><span class="line">一个模块被另一个程序第一次引入时，其主程序将运行。如果我们想在模块被引入时，模块中的某一程序块不执行，我们可以用 __name__ 属性来使该程序块仅在该模块自身运行时执行。</span><br><span class="line">if __name__ == &apos;__main__&apos;:</span><br><span class="line">    print(&apos;程序自身在运行&apos;)</span><br><span class="line">else:</span><br><span class="line">    print(&apos;我来自另一模块&apos;)</span><br></pre></td></tr></table></figure>
<h1 id="dir-函数"><a href="#dir-函数" class="headerlink" title="dir 函数"></a>dir 函数</h1><blockquote>
<p>内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回。<br>如果没有给定参数，那么 dir() 函数会罗列出当前定义的所有名称。<br>在 Python 中万物皆对象，int、str、float、list、tuple等内置数据类型其实也是类，也可以用 dir(int) 查看 int 包含的所有方法。也可以使用 help(int) 查看 int 类的帮助信息。</p>
</blockquote>
<h1 id="包"><a href="#包" class="headerlink" title="包"></a>包</h1><blockquote>
<p>包是一种管理 Python 模块命名空间的形式，采用”点模块名称”。<br>比如一个模块的名称是 A.B， 那么他表示一个包 A中的子模块 B 。<br>就好像使用模块的时候，你不用担心不同模块之间的全局变量相互影响一样，采用点模块名称这种形式也不用担心不同库之间的模块重名的情况。<br>在导入一个包的时候，Python 会根据 sys.path 中的目录来寻找这个包中包含的子目录。<br>目录只有包含一个叫做 <strong>init</strong>.py 的文件才会被认作是一个包，主要是为了避免一些滥俗的名字（比如叫做 string）不小心的影响搜索路径中的有效模块。<br>最简单的情况，放一个空的 <strong>init</strong>.py 文件就可以了。当然这个文件中也可以包含一些初始化代码或者为 <strong>all</strong> 变量赋值。</p>
</blockquote>
<h1 id="第三方模块"><a href="#第三方模块" class="headerlink" title="第三方模块"></a>第三方模块</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">easy_install 和 pip 都是用来下载安装 Python 一个公共资源库 PyPI 的相关资源包的，pip 是 easy_install 的改进版，提供更好的提示信息，删除 package 等功能。老版本的 python 中只有 easy_install，没有pip。</span><br><span class="line">easy_install 打包和发布 Python 包，pip 是包管理。</span><br><span class="line">easy_install 的用法：</span><br><span class="line">安装一个包</span><br><span class="line">easy_install 包名</span><br><span class="line">easy_install &quot;包名 == 包的版本号&quot;</span><br><span class="line">升级一个包</span><br><span class="line">easy_install -U &quot;包名 &gt;= 包的版本号&quot;</span><br><span class="line">pip 的用法：</span><br><span class="line">安装一个包</span><br><span class="line">pip install 包名</span><br><span class="line">pip install 包名 == 包的版本号</span><br><span class="line">升级一个包 （如果不提供version号，升级到最新版本）</span><br><span class="line">pip install —upgrade 包名 &gt;= 包的版本号</span><br><span class="line">删除一个包</span><br><span class="line">pip uninstall 包名</span><br><span class="line">已安装包列表</span><br><span class="line">pip list</span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/blog/2018/09/03/Python-3-高级函数/">
        <span class="nav-arrow">← </span>
        
          Python-3-高级函数
        
      </a>
    
    
      <a class="nav-right" href="/blog/2018/09/03/Python-3-错误和异常/">
        
          Python-3-错误和异常
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#模块"><span class="toc-nav-text">模块</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#导入模块"><span class="toc-nav-text">导入模块</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#name-属性"><span class="toc-nav-text">name 属性</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#dir-函数"><span class="toc-nav-text">dir 函数</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#包"><span class="toc-nav-text">包</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#第三方模块"><span class="toc-nav-text">第三方模块</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'git@gitee.com:sanyuanempire/blog.git/2018/09/03/Python-3-模块/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Python-3-模块",
        owner: "",
        repo: "",
        oauth: {
          client_id: "",
          client_secret: ""
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'git@gitee.com:sanyuanempire/blog.git/2018/09/03/Python-3-模块/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2018 | Proudly powered by <a href="https://sanyuanempire.gitee.io/blog" target="_blank">JinYan</a>
    <br>
    Theme by <a href="https://sanyuanempire.gitee.io/blog">JinYan</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/blog/js/script.js"></script>

  </body>
</html>